package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    // jwt工具类
    private final JwtTool jwtTool;
    // 认证配置
    private final AuthProperties authProperties;
    // 路径匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求、
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求地址
        String path = request.getPath().value();
        //白名单
        List<String> excludePaths = authProperties.getExcludePaths();
        //判断请求地址是否是白名单，是就放行
        for ( String excludePath : excludePaths){
            if (antPathMatcher.match(excludePath, path)){
                return chain.filter(exchange);
            }
        }
        //获取token
        String token = request.getHeaders().getFirst("authorization");
        //判断token是否为空
        if(token == null){
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        ServerHttpResponse response = exchange.getResponse();
        //解析token
        Long userId =null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //把用户id下传给微服务
        request.mutate().header("user-info", userId.toString());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
